package cn.myworld.algorithm.opt;

/**
 * 快慢指针_链表是否有环问题
 */
public class CircleListCheck {

    public static void main(String[] args) {

        Node<String> first = new Node<String>("aa", null);
        Node<String> second = new Node<String>("bb", null);
        Node<String> third = new Node<String>("cc", null);
        Node<String> fourth = new Node<String>("dd", null);
        Node<String> fifth = new Node<String>("ee", null);
        Node<String> six = new Node<String>("ff", null);
        Node<String> seven = new Node<String>("gg", null);

        // 节点之间的指向
        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;
        fifth.next = six;
        six.next = seven;

        // 产生环
        seven.next = third;

        // 判断链表是否有环
        boolean cricle = isCircle(first);
        System.out.println("first链表中是否有环：" + cricle);
    }

    /**
     * 判断链表是否有环
     * @param first 链表首节点
     * @return true为有环，false为无环
     */
    public static boolean isCircle(Node<String> first) {
        // 定义快慢指针
        Node<String> fast = first;
        Node<String> slow = first;
        // 遍历链表，如果快慢指针指向了同一节点，证明有环
        while (fast != null && fast.next != null) {
            // 变换fast和slow
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return true;
            }
        }
        return false;
    }

    /**
     * 节点类
     */
    private static class Node<T> {
        T data;
        Node<T> next;
        public Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }

    }

}
